package com.ms.controller;

import com.ms.annotation.AdminOrOrganizerOnly;
import com.ms.entity.Organizer;
import com.ms.entity.User;
import com.ms.entity.VolunteerActivity;
import com.ms.service.inter.VolunteerActivityService;
import com.ms.utils.SimpleTokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 志愿活动控制器 - 处理志愿活动相关的HTTP请求
 * 包括志愿活动发布、查询、更新等功能
 */
@RestController
@RequestMapping("/va")
public class VolunteerActivityController {

    @Autowired
    private VolunteerActivityService volunteerActivityService;

    /**
     * 创建志愿活动（管理员和主办方功能）
     * @param volunteerActivity 志愿活动信息
     * @param request HTTP请求
     * @return 创建结果
     */
    @PostMapping("/create")
    @AdminOrOrganizerOnly
    public ResponseEntity<Map<String, Object>> createActivity(@RequestBody VolunteerActivity volunteerActivity, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            // 修改权限检查，允许管理员和主办方访问
            if (!(userObj instanceof User) && !(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            // 设置发布人ID
            if (userObj instanceof User) {
                User currentUser = (User) userObj;
                volunteerActivity.setPublisherId(Long.valueOf(currentUser.getUserID()));
            } else if (userObj instanceof Organizer) {
                Organizer currentOrganizer = (Organizer) userObj;
                volunteerActivity.setPublisherId(Long.valueOf(currentOrganizer.getOrId()));
            }
            
            // 设置默认已招募人数为0
            volunteerActivity.setRecruitedNum(0);

            // 保存志愿活动信息
            volunteerActivityService.save(volunteerActivity);

            result.put("success", true);
            result.put("message", "志愿活动创建成功");
            result.put("activity", volunteerActivity);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取志愿活动详情
     * @param activityId 活动ID
     * @return 志愿活动详情
     */
    @GetMapping("/detail")
    public ResponseEntity<Map<String, Object>> getActivity(@RequestParam Long activityId) {
        Map<String, Object> result = new HashMap<>();

        try {
            VolunteerActivity activity = volunteerActivityService.findById(activityId);
            if (activity == null) {
                result.put("success", false);
                result.put("message", "活动不存在");
                return ResponseEntity.badRequest().body(result);
            }

            result.put("success", true);
            result.put("activity", activity);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取活动信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取所有志愿活动
     * @return 所有志愿活动列表
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllActivities() {
        Map<String, Object> result = new HashMap<>();

        try {
            List<VolunteerActivity> activities = volunteerActivityService.findAll();
            result.put("success", true);
            result.put("activities", activities);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取活动列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据状态获取志愿活动列表
     * @param status 状态
     * @return 符合状态的志愿活动列表
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getActivitiesByStatus(@RequestParam Integer status) {
        Map<String, Object> result = new HashMap<>();

        try {
            List<VolunteerActivity> activities = volunteerActivityService.findByStatus(status);
            result.put("success", true);
            result.put("activities", activities);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取活动列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新志愿活动（管理员和主办方功能）
     * @param volunteerActivity 更新的活动信息
     * @param request HTTP请求
     * @return 更新结果
     */
    @PutMapping("/update")
    @AdminOrOrganizerOnly
    public ResponseEntity<Map<String, Object>> updateActivity(
            @RequestBody VolunteerActivity volunteerActivity,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            // 修改权限检查，允许管理员和主办方访问
            if (!(userObj instanceof User) && !(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            Long activityId = volunteerActivity.getActivityId();
            VolunteerActivity existingActivity = volunteerActivityService.findById(activityId);
            if (existingActivity == null) {
                result.put("success", false);
                result.put("message", "活动不存在");
                return ResponseEntity.badRequest().body(result);
            }

            // 更新活动信息
            volunteerActivityService.update(volunteerActivity);

            result.put("success", true);
            result.put("message", "活动更新成功");
            result.put("activity", volunteerActivity);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新活动失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 删除志愿活动（管理员和主办方功能）
     * @param activityId 活动ID
     * @param request HTTP请求
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    @AdminOrOrganizerOnly
    public ResponseEntity<Map<String, Object>> deleteActivity(
            @RequestParam Long activityId,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            // 修改权限检查，允许管理员和主办方访问
            if (!(userObj instanceof User) && !(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            VolunteerActivity activity = volunteerActivityService.findById(activityId);
            if (activity == null) {
                result.put("success", false);
                result.put("message", "活动不存在");
                return ResponseEntity.badRequest().body(result);
            }

            volunteerActivityService.delete(activityId);

            result.put("success", true);
            result.put("message", "活动删除成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除活动失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 获取当前主办方发布的所有志愿活动
     * @param request HTTP请求
     * @return 当前主办方发布的志愿活动列表
     */
    @GetMapping("/my")
    @AdminOrOrganizerOnly
    public ResponseEntity<Map<String, Object>> getMyActivities(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            // 权限检查，只允许主办方访问
            if (!(userObj instanceof Organizer)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            Organizer organizer = (Organizer) userObj;
            Long publisherId = Long.valueOf(organizer.getOrId());
            
            List<VolunteerActivity> activities = volunteerActivityService.findByPublisherId(publisherId);
            result.put("success", true);
            result.put("activities", activities);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取活动列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}